package chuangyi.com.org.DOMIHome;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.Calendar;
import java.util.List;

import chuangyi.com.org.ViewModel.DaoMaster;
import chuangyi.com.org.ViewModel.DaoSession;
import chuangyi.com.org.ViewModel.NetFileCahe;
import chuangyi.com.org.ViewModel.NetFileCaheDao;
import chuangyi.com.org.ViewModel.SearchRecord;
import chuangyi.com.org.ViewModel.SearchRecordDao;
import chuangyi.com.org.ViewModel.User;
import chuangyi.com.org.ViewModel.UserDao;

/**
 * Created by zxh on 16/12/23.
 */

public class DBManager {
    private final static String dbName = "domi";
    private static DBManager mInstance;
    private DaoMaster.DevOpenHelper openHelper;
    private Context context;

    public DBManager(Context context) {
        this.context = context;
        openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
    }

    /**
     * 获取单例引用
     *
     * @param context
     * @return
     */
    public static DBManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (DBManager.class) {
                if (mInstance == null) {
                    mInstance = new DBManager(context);
                }
            }
        }
        return mInstance;
    }

    private static DaoSession getReadableSession(Context context) {
        return getInstance(context).getReadableSession();
    }

    private static DaoSession getWritableSession(Context context) {
        return getInstance(context).getWritableSession();
    }

    /**
     * 获取可读数据库
     */
    private SQLiteDatabase getReadableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
        }
        SQLiteDatabase db = openHelper.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     */
    private SQLiteDatabase getWritableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
        }
        SQLiteDatabase db = openHelper.getWritableDatabase();
        return db;
    }

    private DaoSession getReadableSession() {
        DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
        return daoMaster.newSession();
    }

    private DaoSession getWritableSession() {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        return daoMaster.newSession();
    }

    /**
     * 插入一条记录
     *
     * @param user
     */
    public void insertUser(User user) {
        DaoSession daoSession = getWritableSession();
        UserDao userDao = daoSession.getUserDao();
        userDao.insert(user);
    }

    /**
     * 更新一条记录
     *
     * @param user
     */
    public void updateUser(User user) {
        DaoSession daoSession = getWritableSession();
        UserDao userDao = daoSession.getUserDao();
        userDao.update(user);
    }

    /**
     * 查询用户列表
     */
    public List<User> queryUserList() {
        DaoSession daoSession = getReadableSession();
        UserDao userDao = daoSession.getUserDao();
        QueryBuilder<User> qb = userDao.queryBuilder();
        List<User> list = qb.list();
        return list;
    }

    /**
     * 删除所有用户记录
     *
     * @param
     */
    public void deleteAllUser() {
        DaoSession daoSession = getWritableSession();
        UserDao userDao = daoSession.getUserDao();
        userDao.deleteAll();
    }

    public List<SearchRecord> querySearchRecord() {
        DaoSession daoSession = getReadableSession();
        SearchRecordDao searchRecordDao = daoSession.getSearchRecordDao();
        QueryBuilder<SearchRecord> qb = searchRecordDao.queryBuilder()
                .orderDesc(SearchRecordDao.Properties.Timestamp)
                .limit(8);
        List<SearchRecord> list = qb.list();
        return list;
    }

    public void updateSearchRecord(String record) {
        DaoSession daoSession = getReadableSession();
        SearchRecordDao searchRecordDao = daoSession.getSearchRecordDao();
        QueryBuilder<SearchRecord> qb = searchRecordDao.queryBuilder().where(SearchRecordDao.Properties.Text.eq(record));
        List<SearchRecord> list = qb.list();

        daoSession = getWritableSession();
        searchRecordDao = daoSession.getSearchRecordDao();
        if (list != null && list.size() > 0) {
            SearchRecord searchRecord = list.get(0);
            searchRecord.setTimestamp(Calendar.getInstance().getTimeInMillis());
            searchRecordDao.update(searchRecord);
        } else {
            SearchRecord searchRecord = new SearchRecord();
            searchRecord.setText(record);
            searchRecord.setTimestamp(Calendar.getInstance().getTimeInMillis());
            searchRecordDao.insert(searchRecord);
        }
    }

    public void clearSearchRecord() {
        DaoSession daoSession = getWritableSession();
        SearchRecordDao searchRecordDao = daoSession.getSearchRecordDao();
        searchRecordDao.deleteAll();
    }

    public NetFileCahe getDownloadedFile(String url) {
        DaoSession session = getReadableSession();
        NetFileCaheDao dao = session.getNetFileCaheDao();
        List<NetFileCahe> files = dao.queryBuilder().where(NetFileCaheDao.Properties.Url.eq(url)).list();
        if (files == null || files.size() == 0) {
            return null;
        }
        return files.get(0);
    }

    public void deleteDownloadedFile(NetFileCahe cache){
        DaoSession session = getWritableSession();
        NetFileCaheDao dao = session.getNetFileCaheDao();
        dao.delete(cache);
    }

    public void insertDownloadedFile(String url, String path) {
        if (getDownloadedFile(url) == null) {
            NetFileCahe cache = new NetFileCahe();
            cache.setPath(path);
            cache.setUrl(url);
            DaoSession session = getWritableSession();
            session.getNetFileCaheDao().insert(cache);
        }
    }
}